package com.course.server.utils;

import com.course.server.entity.dto.UserTokenDTO;
import com.course.server.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CustomInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;


    /**
     * @description: TODO 前置拦截
     * @author: 万物皆可喵
     * @date: 2022/9/21 14:48
     * @param: [request, response, handler]
     * @return: boolean
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authToken = request.getHeader("token");
        // 如果没有请求头
        if (authToken == null || authToken.length() == 0) {
            log.info("前置拦截器: 缺少请求头token");
            return false;
        }
        log.info("authToken: {}",authToken );

        UserTokenDTO userTokenDTO = JWTUtil.parseToken(authToken);
        String s = redisService.get(String.valueOf(userTokenDTO.getId()));
        //1.判断请求是否有效
        if (s == null
                || !s.equals(authToken)) {
            log.info("前置拦截器: 请求头token无效");
            return false;
        }

        //2.判断是否需要续期
        if (redisService.getExpireTime(String.valueOf(userTokenDTO.getId())) < 1 * 60 * 30) {
            redisService.set(String.valueOf(userTokenDTO.getId()), authToken);
            log.info("前置拦截器: 更新token信息, id is:{}, user info is:{}", userTokenDTO.getId(), authToken);
        }
        return true;
    }

}
